/**
 * Main file for message channel test
 */

const { BrowserWindow, app, ipcMain, MessageChannelMain } = require('electron')
const pathModule = require('path')

app.whenReady().then(async () => {
  const worker = new BrowserWindow({
    show: false,
    webPreferences: {
      nodeIntegration: true
    }
  })
  await worker.loadFile(pathModule.join(__dirname, 'render', 'worker.html'))

  const mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true
    }
  })
  mainWindow.loadFile(pathModule.join(__dirname, 'render', 'app.html'))
  mainWindow.webContents.openDevTools()

  ipcMain.on('request-worker-channel', (event) => {
    if (event.senderFrame === mainWindow.webContents.mainFrame) {
      console.info('received request-worker-channel')
      const { port1, port2 } = new MessageChannelMain()
      worker.webContents.postMessage('new-client', null, [port1])
      event.senderFrame.postMessage('provide-worker-channel', null, [port2])
    }
  })
})